<template>
  <div>
    <a-drawer
      v-model:visible="visible"
      class="custom-class"
      :title="title"
      placement="right"
      @close="modalClose.close"
      @after-visible-change="afterVisibleChange"
    >
      <div>
        <a-form :label-col="{ span: 12 }" :wrapper-col="{ span: 24 }" label-align="left" :layout="'vertical'">
          <a-form-item label="所属应用" v-bind="validateInfos.appKey">
            <cascader
              v-if="modelRef.appName || isEdit === 'new'"
              :app-type-list="appTypeListTra"
              :width="'313px'"
              :app-type-text="modelRef.appName"
              placeholder="请选择所属应用"
              :is-disabled="title === '详情'"
              @change="appTypeValeChange"
            ></cascader>
          </a-form-item>
          <a-form-item label="上级功能">
            <a-input :disabled="true" :value="upperRol.name" />
          </a-form-item>
          <a-form-item label="标识" v-bind="validateInfos.code">
            <a-input v-model:value="modelRef.code" :disabled="title !== '新增'" placeholder="请输入功能英文标识" />
          </a-form-item>
          <a-form-item label="名称" v-bind="validateInfos.name">
            <a-input v-model:value="modelRef.name" :disabled="isDetl" placeholder="请输入功能名称" />
          </a-form-item>
          <a-form-item label="图标">
            <a-input v-model:value="modelRef.icon" :disabled="isDetl" placeholder="请输入功能图标的链接" />
          </a-form-item>
          <a-form-item label="排序" v-bind="validateInfos.sort">
            <a-input-number v-model:value="modelRef.sort" :disabled="isDetl" :min="0" :precision="0" />
          </a-form-item>
          <a-form-item label="路径">
            <a-input v-model:value="modelRef.path" :disabled="isDetl" placeholder="请输入功能链接" />
          </a-form-item>
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-textarea
              v-model:value="modelRef.remark"
              placeholder="备注"
              :disabled="isDetl"
              :auto-size="{ minRows: 2, maxRows: 2 }"
            />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <div style="display: flex; justify-content: left">
          <div v-show="!isDetl">
            <a-button type="primary" @click="onSubmit">{{ isDetl ? '关闭' : '确定' }}</a-button>
          </div>
          <div style="margin-left: 10px">
            <a-button @click="cancal">{{ isDetl ? '关闭' : '取消' }}</a-button>
          </div>
        </div>
      </template>
    </a-drawer>
    <a-modal v-model:visible="modalClose.modalVisible" title="关闭" @ok="modalClose.modalHandleOk">
      <span>数据未保存,确认关闭吗?</span>
    </a-modal>
  </div>
</template>
<script>
import { defineComponent, toRaw, ref, watch, defineEmits, toRefs, onMounted, reactive, nextTick } from 'vue'
import { Form } from 'ant-design-vue'
import exp from '@/utils/regular'
const useForm = Form.useForm
import { message } from 'ant-design-vue'
import factory from '../factory'
import cascader from './cascader'

export default defineComponent({
  components: { cascader },
  props: {
    isShowEdit: { type: Boolean, default: false },
    isEdit: { type: Number, default: 0 },
    currentItemId: { type: String, default: '' },
    typeList: { type: Array, default: () => [] },
    appTypeListTra: { type: Array, default: () => [] },
    upperRol: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  emits: ['closeEdit', 'deletSuccess', 'editSuccess', 'createSuccess', 'updateSuccess'],
  setup(props, ctx) {
    const { isShowEdit, isEdit, currentItemId, upperRol } = toRefs(props)
    const modelRef = reactive({
      appKey: '',
      appName: '',
      parentId: '',
      code: '',
      name: '',
      sort: '',
      alias: '',
      brandCodes: '',
      clientPath: '',
      componentName: '',
      createTime: '',
      icon: '',
      id: '',
      isCommon: '',
      isGlobal: '',
      keepAlive: '',
      level: '',
      linkTarget: '',
      modifyTime: '',
      path: '',
      remark: '',
      status: '',
      type: '',
      url: '',
    })
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: '请输入名称',
        },
        {
          pattern: exp.name.pattern,
          message: exp.name.message,
        },
        {
          max: 25,
          message: '最多输入25个字符',
        },
      ],
      code: [
        {
          required: true,
          message: '请输入英文标识',
        },
        {
          pattern: exp.key.pattern,
          message: exp.key.message,
        },
        {
          max: 20,
          message: '最多输入20个字符',
        },
      ],
      sort: [
        {
          required: true,
          message: '请输入排序',
        },
      ],
      appKey: [
        {
          required: true,
          message: '请选择所属应用',
        },
      ],
      remark: [
        {
          max: 127,
          message: '最多输入127个字符',
        },
      ],
    })
    const { validate, validateInfos } = useForm(modelRef, rulesRef, {
      //表单验证的输出: 字段 值 提示
      onValidate: (...args) => {
        console.log('表单验证的输出: 字段 值 提示', ...args)
      },
    })

    //==保存==============================
    const onSubmit = () => {
      validate()
        .then(() => {
          //表单验证无误后执行
          save()
        })
        .catch((err) => {
          console.log('error', err)
        })
    }
    const save = () => {
      modelRef.parentId = upperRol.value.id
      if (isEdit.value === 'new') {
        //新增
        factory.create(modelRef).then((res) => {
          visible.value = false
          ctx.emit('createSuccess', modelRef)
          ctx.emit('closeEdit', false)
        })
      } else if (isEdit.value === 'edit') {
        //编辑
        factory.update(modelRef).then((res) => {
          visible.value = false
          ctx.emit('updateSuccess', modelRef)
          ctx.emit('closeEdit', false)
        })
      }
    }

    //== 监视组件显示 =================================
    const visible = ref(false)
    const cancal = () => {
      modalClose.close()
    }
    const title = ref('')
    const isDetl = ref(false)
    watch(isShowEdit, (newValue, oldValue) => {
      if (newValue) {
        switch (isEdit.value) {
          case 'new':
            title.value = '新增'
            break
          case 'edit':
            title.value = '编辑'
            break
          case 'show':
            title.value = '详情'
            isDetl.value = true
            break
        }
        if (title.value !== '新增') {
          factory.getEditDetail(currentItemId.value).then((res) => {
            for (let key in res.data) {
              modelRef[key] = res.data[key]
            }
            visible.value = true

            //备份数据
            modalClose.backupData = JSON.stringify(modelRef)
          })
        } else {
          visible.value = true
        }

        //备份数据
        modalClose.backupData = JSON.stringify(modelRef)
      }
    })
    let backupDate = {} //初始数据
    watch(visible, (newValue, oldValue) => {
      if (newValue) {
        backupDate = JSON.parse(JSON.stringify(modelRef))
      } else {
        ctx.emit('closeEdit', false)
      }
    })

    //==所属应用选择===========================
    const appTypeValeChange = (obj) => {
      modelRef.appKey = obj.value
      modelRef.appName = obj.label
    }
    //==确认关闭对话框======================
    const modalClose = reactive({
      backupData: '',
      close: (e) => {
        if (JSON.stringify(modelRef) !== modalClose.backupData) {
          visible.value = true
          modalClose.modalVisible = true
          return
        }
        visible.value = false
      },
      modalVisible: false,
      modalHandleOk: () => {
        visible.value = false
      },
    })

    return {
      visible,
      onSubmit,
      title,
      cancal,
      validateInfos,
      modelRef,
      isDetl,
      appTypeValeChange,
      modalClose,
    }
  },
})
</script>
<style scoped>
#lulantu {
  width: 300px;
  height: 200px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
}
</style>
